<?php

namespace App\Admin\Eloquent;
use DB;

class Profit extends Model
{
  /**
 * 分润角色代码类别
 *
 * @var string
 */
  const PROFIT_ROLE_CODE = 'profits_role';

  /**
   * 分润阶段代码类别
   *
   * @var string
   */
  const  PROFIT_STAGE_CODE = 'profits_stage';

  /**
   * 分润方式代码类别
   *
   * @var string
   */
  const  PROFIT_MODE_CODE = 'profits_mode';

  /**
   * 模型使用数据库表
   *
   * @var string
   */
  protected $table = 'profits';

  /**
   * 实例化模型可批量赋值
   *
   * @var array
   */
  protected $fillable = ['name','stage', 'mode', 'state'];

  /**
   * 获取分润角色
   *
   * @return \App\Admin\Eloquent\Code
   */
  public static function getRoles()
  {
    return Code::getByTypeId(self:: PROFIT_ROLE_CODE);
  }

  /**
   * 分润角色
   *
   * @return \App\Admin\Eloquent\Code
   */
  public function roles()
  {
    $roleCodes = explode(',', $this->role);
    $roles = [];
    foreach ($roleCodes as $code) {
      $roles[] = Code::findByCodeAndTypeId($code, self::PROFIT_ROLE_CODE);
    }
    return $roles;
  }

  /**
   * 获取分润阶段
   *
   * @return \App\Admin\Eloquent\Code[]
   */
  public static function getStages()
  {
    return Code::getByTypeId(self::PROFIT_STAGE_CODE);
  }

  /**
   * 分润阶段
   *
   * @return \App\Admin\Eloquent\Code
   */
  public function stage()
  {
    return Code::findByCodeAndTypeId($this->stage, self::PROFIT_STAGE_CODE);
  }

  /**
   * 获取分润方式
   *
   * @return \App\Admin\Eloquent\Code[]
   */
  public static function getModes()
  {
    return Code::getByTypeId(self::PROFIT_MODE_CODE);
  }

  /**
   * 分润方式
   *
   * @return \App\Admin\Eloquent\Code
   */
  public function mode()
  {
    return Code::findByCodeAndTypeId($this->mode, self::PROFIT_MODE_CODE);
  }

  /**
   * 判断规则是否被使用
   * @return bool
   */
  public function isUsed(int $id)
  {
    $res=DB::table('projects')
        ->where('profits_cate','=',$id)
        ->first();
    if(empty($res)){
      return false;
    }
    return true;
  }
}